<?php
/**
 * Created by PhpStorm.
 * User: eugene
 * Date: 2018/5/21
 * Time: 09:04
 */

namespace App\Http\Controllers;


use App\Models\Friend;
use App\Models\Member;
use App\Repos\MemberRepo;
use App\Repos\ParkingRepo;
use App\Transformers\MemberTransformer;

class FriendController extends ApiController
{
    protected $memberRepo;
    
    public function __construct(MemberRepo $memberRepo)
    {
        parent::__construct();
        $this->memberRepo = $memberRepo;
    }
    
    public function friends()
    {
        $limit=10;
        
        //获取好友列表
        $uids = Friend::where('user_id',$this->user->id)->orderByDesc('id')->paginate($limit);
    
        $memberTransformer = new MemberTransformer();
        $list = $uids->getCollection()->transform(function($item)use($memberTransformer){
        
            return $memberTransformer->setTransformer('forSimple')->singleData(Member::find($item['to_user_id']));
        });
    
        return $this->setPage($uids->hasMorePages())->success($list);
    }
    
    public function addFriend()
    {
        $to_id = $this->request->input('to_user_id');
        
        if($this->user->id == $to_id)
            return $this->error(1,'不能关注自己');
        if(MemberRepo::checkIsFriend($this->user->id,$to_id)){
            return $this->error(1,'您已经关注过TA了');
        }
        if($this->memberRepo->addFriend($this->user->id,$to_id)){
            return $this->success('关注成功');
        }
        
        return $this->error(1,'关注失败');
    }
    
    
    //随机返回一个好友的车位
    public function search()
    {
        //获取好友列表
        $friends = Friend::where('user_id',$this->user->id)->inRandomOrder()->take(10)->get();
        if($friends->isEmpty())
            return $this->error(1,'您还未关注任何人，添加好友一同加入抢车位吧~');
        
        $random_uids = $friends->filter(function($item){
            return ParkingRepo::getEmptyParks($item['to_user_id']) > 0;
        });
        if($random_uids->isEmpty()){
            return $this->error(1,'无更多车位可用，添加更多好友吧~');
        }
        $random_uid = $random_uids->random()->to_user_id;
        return $this->success(compact('random_uid'));
    }
    
}